/*
 * Funambol is a mobile platform developed by Funambol, Inc.
 * Copyright (C) 2008 Funambol, Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by
 * the Free Software Foundation with the addition of the following permission
 * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
 * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
 * WARRANTY OF NON INFRINGEMENT  OF THIRD PARTY RIGHTS.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, see http://www.gnu.org/licenses or write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA.
 *
 * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
 * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public License
 * version 3, these Appropriate Legal Notices must retain the display of the
 * "Powered by Funambol" logo. If the display of the logo is not reasonably
 * feasible for technical reasons, the Appropriate Legal Notices must display
 * the words "Powered by Funambol".
 */


#import <UIKit/UIKit.h>

#import "common.h"
#import "SettingsSingleView.h"
#import "base/Log.h"
#import "AccountView.h"
#import "ContactsSettingsView.h"
#import "LogSettingsView.h"
#import "AboutView.h"
#import "FunambolAPI.h"

#import "RecoverView.h"
#import "CleanUpView.h"
// TODO : REMOVE THIS HACK WHEN CLEANUP PAGE IS IMPLEMENTED IS WORKING
//#define CleanupView RecoverView
//#define didClickCleanup didClickRecover

#import "FunambolAPI.h"

#import "UIController.h"

#import "customs.h"

//static NSString *kCellIdentifier = @"MyIdentifier";

@implementation SettingsSingleView

- (id)init {
  
	self = [super init];
	if (self)
	{
		// this title will appear in the navigation bar
		self.title = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
		
		menuList = [[NSMutableArray alloc] init];
	}
    funBlue = [[UIColor alloc] initWithRed:0.0 green:0.4 blue:0.9 alpha:1.0];
	return self;
}

- (void) loadView{
    UIView *contentView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
	self.view = contentView;
	[contentView release];
	
	self.view.autoresizesSubviews = YES;
    [self setTitle:NSLocalizedString(@"Settings",@"Settings")];
    small_font = [UIFont systemFontOfSize:15];

    usernameLabel = [[UILabel alloc] initWithFrame:CGRectMake(140.0, 7.0, 140.0, 25.0)];
    [usernameLabel setFont:small_font];
    [usernameLabel setTextAlignment:UITextAlignmentRight];
    [usernameLabel  setTextColor:funBlue];
    
    
    contactsLabel = [[UILabel alloc] initWithFrame:CGRectMake(140.0, 7.0, 140.0, 25.0)];
    [contactsLabel setFont:small_font];
    [contactsLabel setTextAlignment:UITextAlignmentRight];
    [contactsLabel  setTextColor:funBlue];
    
    [self addComponents];
    
}

- (void)viewWillAppear:(BOOL)animated
{
	// this UIViewController is about to re-appear, make sure we remove the current selection in our table view
    lastSelection = [settingsTable indexPathForSelectedRow];
	[settingsTable deselectRowAtIndexPath:lastSelection animated:NO];
}

- (void) viewDidAppear:(BOOL)animated{
    NSString* URL;
    NSString* username;
    NSString* password; 
    
    [[FunambolAPI getInstance] loadSyncConfig:&URL username:&username password:&password];
    
    if([username isEqualToString:@""] || [password isEqualToString:@""]){
        UIViewController *targetViewController = [[menuList objectAtIndex: 0] objectForKey:@"viewController"];
        [[self navigationController] pushViewController:targetViewController animated:YES];
    }
    
    StringBuffer urlstring([URL UTF8String]);
    if((urlstring.find(" ") != StringBuffer::npos)||
       (urlstring.find("<") != StringBuffer::npos)||
       (urlstring.find(">") != StringBuffer::npos)){
        UIViewController *targetViewController = [[menuList objectAtIndex: 0] objectForKey:@"viewController"];
        [[self navigationController] pushViewController:targetViewController animated:YES];
    } 
    
    [usernameLabel setText:username];
    
    [URL      release];
    [username release];
    [password release];
    
    NSString* contactsync = [[FunambolAPI getInstance] getSync:@"addressbook"];
    
    if([contactsync isEqualToString:@"none"]){
        [contactsLabel setText:NSLocalizedString(@"Disabled",@"Disabled")];
    }else{
        [contactsLabel setText:NSLocalizedString(@"Enabled",@"Enabled")];
    }
    
    [contactsync release];
    
	// this UIViewController is about to re-appear, make sure we remove the current selection in our table view
	NSIndexPath *indexPath = lastSelection;
    
    if(!indexPath)
        return;
        
    switch (indexPath.section) {
        case 2:
            if (!CUSTOM_LOG_SEPARATE_GROUP && CUSTOM_CLEANUP || CUSTOM_RECOVER)
            {
                switch (indexPath.row) {
                    case 1:
                        if (CUSTOM_CLEANUP) {
                            // Go back and init cleanup
                            UIViewController *targetViewController = [[menuList objectAtIndex: 3] objectForKey:@"viewController"];
                            if ([((CleanUpView*)targetViewController) didClickCleanup])
                            {
                                [[UIController getInstance] cleanupContacts];
                                [[self navigationController] popViewControllerAnimated:YES];
                            }
                        } else if (CUSTOM_RECOVER) {
                            UIViewController *targetViewController = [[menuList objectAtIndex: 4] objectForKey:@"viewController"];
                            if ([((RecoverView*)targetViewController) didClickRecover])
                            {
                                // Go back and init recover
                                [[UIController getInstance] recoverContacts];
                                [[self navigationController] popViewControllerAnimated:YES];
                            }
                        }
                        break;
                    case 2:
                        if (CUSTOM_RECOVER)
                        {
                            UIViewController *targetViewController = [[menuList objectAtIndex: 4] objectForKey:@"viewController"];
                            if ([((RecoverView*)targetViewController) didClickRecover])
                            {
                                // Go back and init recover
                                [[UIController getInstance] recoverContacts];
                                [[self navigationController] popViewControllerAnimated:YES];
                            }
                        }
                        break;
                    default:
                        break;
                }
            }
            
            break;
        case 3:
            if(CUSTOM_LOG_SEPARATE_GROUP && CUSTOM_CLEANUP || CUSTOM_RECOVER)
            {
                switch (indexPath.row) {
                    case 0:
                        if (CUSTOM_CLEANUP) {
                            // Go back and init cleanup
                            UIViewController *targetViewController = [[menuList objectAtIndex: 3] objectForKey:@"viewController"];
                            if ([((CleanUpView*)targetViewController) didClickCleanup])
                            {
                                [[UIController getInstance] cleanupContacts];
                                [[self navigationController] popViewControllerAnimated:YES];
                            }
                        } else if (CUSTOM_RECOVER) {
                            UIViewController *targetViewController = [[menuList objectAtIndex: 4] objectForKey:@"viewController"];
                            if ([((RecoverView*)targetViewController) didClickRecover])
                            {
                                // Go back and init recover
                                [[UIController getInstance] recoverContacts];
                                [[self navigationController] popViewControllerAnimated:YES];
                            }
                        }
                        break;
                    case 1:
                        if (CUSTOM_RECOVER)
                        {
                            UIViewController *targetViewController = [[menuList objectAtIndex: 4] objectForKey:@"viewController"];
                            if ([((RecoverView*)targetViewController) didClickRecover])
                            {
                                // Go back and init recover
                                [[UIController getInstance] recoverContacts];
                                [[self navigationController] popViewControllerAnimated:YES];
                            }
                        }
                        break;
                    default:
                        break;
                }
            }
            break;
        default:
            break;
    }

	[settingsTable deselectRowAtIndexPath:indexPath animated:NO];
}

/*
 * 0 account
 * 1 Contact 
 * 2 log
 * 3 cleanup
 * 4 recover
 * 5 about
 */

- (void) addComponents{
    
    //menulist index 0
    AccountView* accountview = [[AccountView alloc] init];
    [menuList addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                         NSLocalizedString(@"Account", @""), @"title",
                         accountview, @"viewController",
                         nil]];
	[accountview release];
    
    //menulist index 1
    ContactsSettingsView* contactview = [[ContactsSettingsView alloc] init];
    [menuList addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                         NSLocalizedString(@"Contact Settings", @""), @"title",
                         contactview, @"viewController",
                         nil]];
	[contactview release];
    
    LogSettingsView* logsettingsview = [[LogSettingsView alloc] init];
    [menuList addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                         NSLocalizedString(@"Log Settings", @""), @"title",
                         logsettingsview, @"viewController",
                         nil]];
	[logsettingsview release];
    
        //menulist index 2
        CleanUpView * cleanupView = [[CleanUpView alloc] init];
        [menuList addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                             NSLocalizedString(@"Cleanup", @""), @"title",
                             cleanupView, @"viewController",
                             nil]];
        [cleanupView release];
        RecoverView * recoverView = [[RecoverView alloc] init];
        [menuList addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                             NSLocalizedString(@"Recover", @""), @"title",
                             recoverView, @"viewController",
                             nil]];
        [recoverView release];
    
    
    AboutView* aboutview = [[AboutView alloc] init];
    [menuList addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                         NSLocalizedString(@"Account", @""), @"title",
                         aboutview, @"viewController",
                         nil]];
	[aboutview release];

	settingsTable = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped]; 
	settingsTable.delegate = self;
    settingsTable.dataSource = self;
	settingsTable.rowHeight = 40;
    [settingsTable reloadData];
	//Main Navigation Bar!
    
    //usernameLabel = [[UILabel alloc] initWithFrame:CGRectMake(140.0, 7.0, 140.0, 25.0)];
    
    

	[self addAccountTable];

	[self addSourcesTable];

	[self addLogTable];
	
	[self addAboutTable];
    
    [self addCleanupTable];
    
    [self addRecoverTable];
	
	[self.view addSubview:settingsTable];


}

- (void) addAccountTable{
	accountCell =  [[UITableViewCell alloc]init];
    [[accountCell textLabel] setText:NSLocalizedString(@"Account",@"Account")];
    [[accountCell imageView] setImage:[UIImage imageNamed: @"worksettings.png"]];
    [[accountCell textLabel] setTextAlignment:UITextAlignmentLeft];
    [accountCell addSubview:usernameLabel];
}

- (void) addSourcesTable{
    
	contactsCell =  [[UITableViewCell alloc]init];
    [[contactsCell textLabel] setText:NSLocalizedString(@"Contacts",@"Contacts")];
    [[contactsCell imageView] setImage:[UIImage imageNamed: @"icon_contacts_small.png"]];
    [[contactsCell textLabel] setTextAlignment:UITextAlignmentLeft];
    //[contactsCell addSubview:contactsLabel];
    
	calendarsCell =  [[UITableViewCell alloc]init];
    [[calendarsCell textLabel] setText:NSLocalizedString(@"Calendar",@"Calendar")];
    [[calendarsCell textLabel] setTextColor:[UIColor grayColor]];
    [[calendarsCell imageView] setImage:[UIImage imageNamed: @"icon_calendar_small_g.png"]];
    
	tasksCell =  [[UITableViewCell alloc]init];
    [[tasksCell textLabel] setText:NSLocalizedString(@"Tasks",@"Tasks")];
    [[tasksCell textLabel] setTextColor:[UIColor grayColor]];
    [[tasksCell imageView] setImage:[UIImage imageNamed: @"icon_tasks_small_g.png"]];
    
	notesCell =  [[UITableViewCell alloc]init];
    [[notesCell textLabel] setText:NSLocalizedString(@"Notes",@"Notes")];
    [[notesCell textLabel] setTextColor:[UIColor grayColor]];
    [[notesCell imageView] setImage:[UIImage imageNamed: @"icon_notes_small_g.png"]];
}

- (void) addLogTable{
    
	logCell =  [[UITableViewCell alloc]init];
    [[logCell textLabel] setText:NSLocalizedString(@"Log",@"Log")];
    [[logCell imageView] setImage:[UIImage imageNamed: @"icon_log_small.png"]];
}

- (void) addAboutTable{
    
	aboutCell =  [[UITableViewCell alloc]init];
    [[aboutCell textLabel] setText:[NSLocalizedString(@"AboutC",@"About ") stringByAppendingString:NSLocalizedString(@"AppName",@"Funambol")]];
	[[aboutCell imageView] setImage:[UIImage imageNamed: @"icon_logo_small.png"]];
}

- (void) addCleanupTable{
    
	cleanupCell =  [[UITableViewCell alloc]init];
    [[cleanupCell textLabel] setText:NSLocalizedString(@"Cleanup",@"Cleanup")];
	[[cleanupCell imageView] setImage:[UIImage imageNamed: @"icon_cleanup_small.png"]];
}

- (void) addRecoverTable{

	recoverCell =  [[UITableViewCell alloc]init];
    [[recoverCell textLabel] setText:NSLocalizedString(@"Recover",@"Recover")];
	[[recoverCell imageView] setImage:[UIImage imageNamed: @"icon_recover_small.png"]];
}

- (void) reload {
}

- (UITableViewCellAccessoryType)tableView:(UITableView *)settingsTable accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 1:
            switch (indexPath.row) {
                case 0:
                    return UITableViewCellAccessoryDisclosureIndicator;
                default:
                    return UITableViewCellAccessoryNone;
            }
            break;
        default:
            return UITableViewCellAccessoryDisclosureIndicator;
    }
    return UITableViewCellAccessoryDisclosureIndicator;
}


- (UITableViewCell *)tableView:(UITableView *)settingsTable cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
            //account table section
        case 0:
            switch (indexPath.row) {
                case 0:
                    return accountCell;
                default:
                    break;
            }
            break;
            //sources table section
        case 1:
            switch (indexPath.row) {
                case 0:
                    return contactsCell;
                case 1:
                    return calendarsCell;
                case 2:
                    return tasksCell;
                case 3:
                    return notesCell;
                default:
                    break;
            }
            // cleanup/recover
        case 2:
            switch (indexPath.row) {
                case 0:
                    return logCell;
                case 1:
                    if (CUSTOM_CLEANUP){
                        return cleanupCell;
                    } else if (CUSTOM_RECOVER){
                        return recoverCell;
                    }
                case 2:
                    return recoverCell;
                default: 
                    break;
            }

            // about table section
        case 3:
            switch (indexPath.row) {
                case 0:
                    if(CUSTOM_LOG_SEPARATE_GROUP){
                        if (CUSTOM_CLEANUP)
                            return cleanupCell;
                        else if (CUSTOM_RECOVER)
                            return recoverCell;
                    }else{
                        return aboutCell;
                    }
                case 1:
                    return recoverCell;        
                default:
                    break;
            }
        case 4:
            switch (indexPath.row) {
                case 0:
                    return aboutCell;
                default:
                    break;
            }

        default:
            
            break;
    }
    return nil;
}

- (NSInteger)tableView:(UITableView *)settingsTable numberOfRowsInSection:(NSInteger)section {

    switch (section) {
		case 0:
			return 1;
		case 1:
            return 1;
        case 2:
            if(CUSTOM_LOG_SEPARATE_GROUP){
                return 1;
            }else{
                switch ((CUSTOM_CLEANUP?1:0)*1 + (CUSTOM_RECOVER?1:0)*2)
                {
                    case 0: // Neither clean nor recover - it will be Log
                        return 1;
                    case 1:
                        return 2;
                    case 2:
                        return 2;
                    case 3:
                        return 3;
                default: 
                        break;
                }
            }
		case 3:
            if(CUSTOM_LOG_SEPARATE_GROUP){
                switch ((CUSTOM_CLEANUP?1:0)*1 + (CUSTOM_RECOVER?1:0)*2)
                {
                    case 0: // Neither clean nor recover - it will be Log
                        return 1;
                    case 1:
                        return 1;
                    case 2:
                        return 1;
                    case 3:
                        return 2;
                    default: 
                        break;
                }
            }else{
                return 1;
            }
        case 4:
            return 1;
		default:
			break;
	}
    return 0;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)settingsTable {
    if (CUSTOM_LOG_SEPARATE_GROUP){
        return 5;
    }else{
        return 4;
    }
    return 4;
}


/*
 * 0 account
 * 1 Contact 
 * 2 log
 * 3 cleanup
 * 4 recover
 * 5 about
 */

- (void)tableView:(UITableView *)settingsTable didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
	UIViewController *targetViewController;
	UIViewController *targetViewController2;
	UIViewController *targetViewController3;

    switch (indexPath.section){
        case 0://account
            switch (indexPath.row) {
                case 0:
                    targetViewController = [[menuList objectAtIndex: 0] objectForKey:@"viewController"];
                    [[self navigationController] pushViewController:targetViewController animated:YES];
                    break;
                default:
                    break;
            }
            break;
        case 1://contact
            switch (indexPath.row) {
                case 0:
                    targetViewController = [[menuList objectAtIndex: 1] objectForKey:@"viewController"];
                    [[self navigationController] pushViewController:targetViewController animated:YES];
                    break;
                default:
                    break;
            }
            break;
        case 2://log cleanup recover
            switch (indexPath.row) {
                case 0:
                    targetViewController = [[menuList objectAtIndex: 2] objectForKey:@"viewController"];
                    [[self navigationController] pushViewController:targetViewController animated:YES];
                    break;
                case 1:
                    if(CUSTOM_CLEANUP){
                        UIViewController *targetViewController2 = [[menuList objectAtIndex: 3] objectForKey:@"viewController"];
                        [[self navigationController] pushViewController:targetViewController2 animated:YES];
                    }else if (CUSTOM_RECOVER){
                        UIViewController *targetViewController3 = [[menuList objectAtIndex: 4] objectForKey:@"viewController"];
                        [[self navigationController] pushViewController:targetViewController3 animated:YES];
                    }
                    break;
                case 2:
                    targetViewController3 = [[menuList objectAtIndex: 4] objectForKey:@"viewController"];
                    [[self navigationController] pushViewController:targetViewController3 animated:YES];
                    break;
                default:
                    break;
            }
            break;
        case 3://  about
            if(CUSTOM_LOG_SEPARATE_GROUP){
                switch (indexPath.row) {
                    case 0:
                        if(CUSTOM_CLEANUP){
                            UIViewController *targetViewController2 = [[menuList objectAtIndex: 3] objectForKey:@"viewController"];
                            [[self navigationController] pushViewController:targetViewController2 animated:YES];
                        }else if (CUSTOM_RECOVER){
                            UIViewController *targetViewController3 = [[menuList objectAtIndex: 4] objectForKey:@"viewController"];
                            [[self navigationController] pushViewController:targetViewController3 animated:YES];
                        }
                        break;
                    case 1:
                        targetViewController3 = [[menuList objectAtIndex: 4] objectForKey:@"viewController"];
                        [[self navigationController] pushViewController:targetViewController3 animated:YES];
                        break;
                    default:
                        break;
                }
            }else{
                switch (indexPath.row) {
                    case 0:
                        targetViewController = [[menuList objectAtIndex: 5] objectForKey:@"viewController"];
                        [[self navigationController] pushViewController:targetViewController animated:YES];
                        break;
                        
                    default:
                        break;
                }
            }
            break;
        case 4:
            switch (indexPath.row) {
                case 0:
                    targetViewController = [[menuList objectAtIndex: 5] objectForKey:@"viewController"];
                    [[self navigationController] pushViewController:targetViewController animated:YES];
                    break;
                    
                default:
                    break;
            }
        default:
            break;
            
    }
}


- (void)dealloc {
    [menuList release];
    
    [settingsTable release];
    
	[accountCell release];
	[contactsCell release];
	[calendarsCell release];
	[tasksCell release];
	[notesCell release];
	[logCell release];	
	[aboutCell release];

    [recoverCell release];
    [cleanupCell release];
    
    [contactsLabel release];
    [usernameLabel release];
    [funBlue release];
    [small_font release];

    [super dealloc];
}



@end
